package org.foreningsgatan.mercenaries.rendering;

import java.util.LinkedList;
import java.util.List;

import org.foreningsgatan.mercenaries.Configuration;
import org.foreningsgatan.mercenaries.model.GroundDecal;
import org.foreningsgatan.modular.lightsources.LightMap;
import org.foreningsgatan.modular.lightsources.RGB;
import org.foreningsgatan.modules.glcore.graphics.Alignment;
import org.foreningsgatan.modules.glcore.graphics.BlendMode;
import org.foreningsgatan.modules.glcore.graphics.GLGraphics;

/**
 * Copyright (c) 2008 Joakim Back
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * @author Joakim Back
 *
 */
public class GroundDecalRenderer implements Renderer {
	private List<GroundDecal> mDecals;
	
	private List<GroundDecal> mVisibleDecals;

	private LightMap mLightMap;
	
	public GroundDecalRenderer() {
		mVisibleDecals = new LinkedList<GroundDecal>();
	}
	
	public void update(List<GroundDecal> pDecals, LightMap pLightMap) {
		this.mDecals = pDecals;
		this.mLightMap = pLightMap;
	}
	
	public void render(GLGraphics g, TileClippingRect rect, ScrollPosition pos,
			boolean hasScrolled) {
		if (hasScrolled) {
			mVisibleDecals.clear();
			
			for (GroundDecal d: mDecals) {
				float x = RenderUtils.toScreenCoord(d.getX(), Orientation.HORIZONTAL, pos);
				float y = RenderUtils.toScreenCoord(d.getY(), Orientation.VERTICAL, pos);
				
				if (g.inView(x, y, Configuration.sFrameInviewMargin)) {
					mVisibleDecals.add(d);
				}
			}
		}
		
		for (GroundDecal d: mVisibleDecals) {
			float x = RenderUtils.toScreenCoord(d.getX(), Orientation.HORIZONTAL, pos);
			float y = RenderUtils.toScreenCoord(d.getY(), Orientation.VERTICAL, pos);
			
			RGB rgb = mLightMap.get((int) d.getX(), (int) d.getY());
			
			g.drawFrames(x, y, d.getFrames(), Alignment.CENTER,
					1.0f, rgb.getRGB(), BlendMode.ALPHA);
		}
	}

}
